package com.mhz.mvc.cfg;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * mvc配置文件读取
 * @author mhz
 *
 */
public class Cfg {
	private Map<String, ActionCfg> actionCfgs = new HashMap<String, ActionCfg>();
	public static Cfg getInstance(InputStream xml) {
		try {
			SAXReader reader = new SAXReader();
			Document doc = reader.read(xml);
			Element root = doc.getRootElement();
			List<Element> list = root.elements("action");
			Cfg cfg = new Cfg();

			// 
			for (Element e : list) {
				String name = e.attribute("name").getValue();
				String cls = e.attribute("class").getValue();
				ActionCfg actionCfg = new ActionCfg();
				actionCfg.setName(name);
				actionCfg.setClassPath(cls);

				// 
				List<Element> list2 = e.elements("interceptor");
				for (Element e2 : list2) {
					String clazz2 = e2.attribute("class").getValue();
					InterceptorCfg interceptorCfg = new InterceptorCfg();
					interceptorCfg.setClazz(clazz2);
					actionCfg.addInterceptorCfg(interceptorCfg);
				}
				//返回结果
				List<Element> list1 = e.elements("result");
				for (Element e1 : list1) {
					String name1 = e1.attribute("name").getValue();
					String type1 = e1.attribute("type").getValue();
					String value1 = e1.getText().trim();
					ResultCfg resultCfg = new ResultCfg();
					resultCfg.setName(name1);
					resultCfg.setValue(value1);
					resultCfg.setType(type1);
					actionCfg.addResultCfg(resultCfg);
				}
				cfg.actionCfgs.put(actionCfg.getName(), actionCfg);
			}
			return cfg;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public ActionCfg getActionCfg(String name) {
		return actionCfgs.get(name);
	}
}
